<template>
  <div>
    <el-form :model="formItem" label-width="100px" size="mini">
      <el-form-item label="名称">
        <el-input v-model="formItem.s_name.value" placeholder="请输入名称..." />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formItem.s_status.value" filterable clearable placeholder="请选择资产状态">
          <el-option v-for="(item) in assetStatus" :key="item.code" :label="item.name" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="!isConsumption" :label="isSl ? '资产卡片' : '原始编码'">
        <el-input v-model="formItem.s_originalCode.value" :placeholder="isSl ? '资产卡片' : '原始编码'" />
      </el-form-item>
      <el-form-item label="购置日期">
        <el-date-picker
          v-model="timeRangePurchaseDate"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          value-format="timestamp"
        />
      </el-form-item>
      <el-form-item label="金额">
        <el-input v-model="formItem.s_money.value" type="number" placeholder="请输入内容">
          <el-select slot="prepend" v-model="formItem.s_selectMoney.value" class="select_input" placeholder="请选择" style="width:90px;">
            <el-option v-for="(item) in dataCompare" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item v-if="!isConsumption" label="位置">
        <treeselect
          v-model="formItem.s_location.value"
          :multiple="false"
          :options="availableLocations"
          :disable-branch-nodes="true"
          placeholder="请选择位置"
        />
      </el-form-item>
      <el-form-item label="部门">
        <treeselect
          v-model="formItem.s_managementOrgCode.value"
          :multiple="false"
          :options="availableOganizations"
          :disable-branch-nodes="true"
          placeholder="请选择部门"
        />
      </el-form-item>
      <el-form-item label="使用人">
        <el-input v-model="formItem.s_managementUserName.value" placeholder="请输入使用人姓名..." />
      </el-form-item>
      <el-form-item v-if="typeSearchShow" label="资产分类">
        <treeselect
          v-model="assetTypeCode"
          :multiple="false"
          :options="typeOptions"
          placeholder="选择资产分类"
        />
      </el-form-item>
      <el-form-item v-if="!isConsumption" label="维保开始">
        <el-date-picker
          v-model="timeRangeMaintenanceStart"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          value-format="timestamp"
        />
      </el-form-item>
      <el-form-item v-if="!isConsumption" label="维保结束">
        <el-date-picker
          v-model="timeRangeMaintenanceEnd"
          type="daterange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          value-format="timestamp"
        />
      </el-form-item>
      <el-form-item label="用途">
        <el-input v-model="formItem.s_purpose.value" placeholder="请输入用途..." />
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { isObject } from '@neu/biz-core/utils/utils'
import { clone } from '@neu/biz-core/utils/utils'
import { tree as typeTree } from '@neu/dcam-ui/api/assetType'
import { tree as locationTree } from '@neu/dcam-ui/api/location'
import { formatDate } from '@neu/biz-core/utils/utils'
import belongs from '@neu/dcam-ui/mixins/belongs'
import { ASSET_STATUS } from '@neu/dcam-ui/utils/constants'
import { tree as orgTree } from '@neu/auth-ui/api/organization'

// 定义一个查询表单原始项
const formItem = {
  /** 名称 */
  s_name: { value: '', label: '名称', valueName: '' },
  /** 原始资产编号 */
  s_originalCode: { value: '', label: '原始资产编号', valueName: '' },
  /** 位置 */
  s_location: { value: null, label: '位置', valueName: null },
  /** 大分类 */
  s_bigTypeCode: { value: null, label: '大分类', valueName: '' },
  /** 中分类 */
  s_middleTypeCode: { value: null, label: '中分类', valueName: '' },
  /** 小分类 */
  s_smallTypeCode: { value: null, label: '小分类', valueName: '' },
  /** 金额 */
  s_money: { value: '', label: '金额', valueName: '' },
  /** 金额比较 */
  s_selectMoney: { value: '', label: '操作符', valueName: '', hidden: true },
  /** 维保开始时间的起止范围 */
  s_maintenanceStartBegin: { value: '', label: '维保开始起', valueName: '' },
  s_maintenanceStartEnd: { value: '', label: '维保开始止', valueName: '' },
  /** 维保结束时间的起止范围 */
  s_maintenanceEndBegin: { value: '', label: '维保结束起', valueName: '' },
  s_maintenanceEndEnd: { value: '', label: '维保结束止', valueName: '' },
  // 所属
  s_belongs: { value: '', label: '所属', valueName: '', hidden: true },
  // 是否加锁
  s_locked: { value: null, label: '是否加锁', valueName: '', hidden: true },
  // 分类
  s_categories: { value: '', label: '分类', valueName: '', hidden: true },
  /** 购置日期的起止范围 */
  s_purchaseDateBegin: { value: '', label: '购置日期起', valueName: '' },
  s_purchaseDateEnd: { value: '', label: '购置日期止', valueName: '' },
  /** 用途 */
  s_purpose: { value: '', label: '用途', valueName: '' },
  /** 使用人 */
  s_managementUserName: { value: '', label: '使用人', valueName: '' },
  /** 状态 */
  s_status: { value: '', label: '状态', valueName: '', hidden: false },
  /** 状态集合 */
  s_statusCode: { value: '', label: '状态集合', valueName: '', hidden: true },
  /** 组织机构 */
  s_orgIds: { value: '', label: '组织机构', valueName: '', hidden: true },
  /** 规格型号 */
  s_specifications: { value: '', label: '规格型号', valueName: '', hidden: true },
  /** 部门 */
  s_managementOrgCode: { value: null, label: '部门', valueName: '', hidden: false }
}

export default {
  name: 'FixedAssetTableFilter',
  mixins: [belongs],
  props: {
    // filter: {
    //   required: true,
    //   type: Function
    // },
    lockCodes: {
      type: String,
      default: ''
    },
    status: {
      type: String,
      default: ''
    },
    statusCode: {
      type: String,
      default: ''
    },
    orgIds: {
      type: String,
      default: ''
    },
    orgSearchShow: {
      type: Boolean,
      default: true
    },
    // belongs: {
    //   type: String,
    //   default: null,
    //   required: true
    // },
    // categories: {
    //   type: String,
    //   default: null,
    //   required: true
    // },
    locked: {
      type: Boolean,
      default: null
    },
    smallTypeCode: {
      type: String,
      default: ''
    },
    typeSearchShow: {
      type: Boolean,
      default: true
    },
    specifications: {
      type: String,
      default: ''
    },
    statusSearchShow: {
      type: Boolean,
      default: true
    },
    managementOrgCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 类型
      assetTypeCode: null,
      /** 数值型比较 */
      dataCompare: [
        { label: '>', value: 'gt' }, { label: '>=', value: 'gte' }, { label: '==', value: 'eq' }, { label: '<', value: 'lt' }, { label: '<=', value: 'lte' }
      ],
      /** 时间选择器 */
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      /** 存储时间范围 */
      timeRangeMaintenanceStart: [],
      timeRangeMaintenanceEnd: [],
      timeRangePurchaseDate: [],
      formItem: {
        ...formItem
      },
      /** 资产机房树 */
      availableLocations: [],
      /** 资产类型树 */
      typeOptions: [],
      // 类型扁平化
      flattenTypeTreeData: [],
      /** 资产状态 */
      assetStatus: [...ASSET_STATUS],
      /** 使用部门 */
      availableOganizations: []
    }
  },
  computed: {
    isSl: function() {
      return this.belongs === 'sl' && this.categories !== '3'
    },
    isKj: function() {
      return this.belongs === 'kj' && this.categories !== '3'
    },
    isConsumption: function() {
      return this.categories === '3'
    }
  },
  created() {
    typeTree(this.belongs, this.categories).then(response => {
      const result = response.data
      this.typeOptions = result
      this.flattenTypeTreeData = this.flattenTreeDataClosure(result)
    })
    locationTree(this.belongs).then(response => {
      this.availableLocations = response.data
    })
    orgTree(this.belongs).then(response => {
      this.availableOganizations = [response.data]
    })
  },
  methods: {
    // 查询按钮点击事件处理
    search: function() {
      if (this.timeRangePurchaseDate.length !== 0) {
        this.formItem.s_purchaseDateBegin.value = this.timeRangePurchaseDate[0]
        this.formItem.s_purchaseDateBegin.valueName = formatDate(this.timeRangePurchaseDate[0], 'YYYY-MM-DD')
        this.formItem.s_purchaseDateEnd.value = this.timeRangePurchaseDate[1]
        this.formItem.s_purchaseDateEnd.valueName = formatDate(this.timeRangePurchaseDate[1], 'YYYY-MM-DD')
      }
      if (this.timeRangeMaintenanceStart.length !== 0) {
        this.formItem.s_maintenanceStartBegin.value = this.timeRangeMaintenanceStart[0]
        this.formItem.s_maintenanceStartBegin.valueName = formatDate(this.timeRangeMaintenanceStart[0], 'YYYY-MM-DD')
        this.formItem.s_maintenanceStartEnd.value = this.timeRangeMaintenanceStart[1]
        this.formItem.s_maintenanceStartEnd.valueName = formatDate(this.timeRangeMaintenanceStart[1], 'YYYY-MM-DD')
      }
      if (this.timeRangeMaintenanceEnd.length !== 0) {
        this.formItem.s_maintenanceEndBegin.value = this.timeRangeMaintenanceEnd[0]
        this.formItem.s_maintenanceEndBegin.valueName = formatDate(this.timeRangeMaintenanceEnd[0], 'YYYY-MM-DD')
        this.formItem.s_maintenanceEndEnd.value = this.timeRangeMaintenanceEnd[1]
        this.formItem.s_maintenanceEndEnd.valueName = formatDate(this.timeRangeMaintenanceEnd[0], 'YYYY-MM-DD')
      }

      const value = this.formItem.s_money.value
      if (this.formItem.s_money.value !== '' && this.formItem.s_selectMoney.value !== '') {
        this.formItem.s_money.value = this.formItem.s_money.value + '|' + this.formItem.s_selectMoney.value
      }

      const locations = this.availableLocations.filter(t => {
        return t.code === this.formItem.s_location.value
      })
      this.formItem.s_location.valueName = locations.length === 1 ? locations[0].title : this.formItem.s_location.value

      // 类型拆分
      if (this.assetTypeCode) {
        const trees = this.findParent(this.assetTypeCode, this.flattenTypeTreeData)

        if (trees[0]) {
          this.formItem.s_bigTypeCode.value = trees[0].code
          this.formItem.s_bigTypeCode.valueName = trees[0].name
          this.formItem.s_smallTypeCode.value = ''
          this.formItem.s_smallTypeCode.valueName = ''
          this.formItem.s_smallTypeCode.value = ''
          this.formItem.s_middleTypeCode.valueName = ''
        }

        if (trees[1]) {
          this.formItem.s_middleTypeCode.value = trees[1].code
          this.formItem.s_middleTypeCode.valueName = trees[1].name
          this.formItem.s_smallTypeCode.value = ''
          this.formItem.s_smallTypeCode.valueName = ''
        }

        if (trees[2]) {
          this.formItem.s_smallTypeCode.value = trees[2].code
          this.formItem.s_smallTypeCode.valueName = trees[2].name
        }
      }
      this.formItem.s_belongs.value = this.belongs
      this.formItem.s_locked.value = this.locked
      this.formItem.s_categories.value = this.categories
      // this.formItem.s_status.value = this.status
      this.formItem.s_statusCode.value = this.statusCode
      this.formItem.s_orgIds.value = this.orgIds
      this.formItem.s_specifications.value = this.specifications

      if (this.managementOrgCode) {
        this.formItem.s_managementOrgCode.value = this.managementOrgCode
      }

      /** 存放查询条件 */
      this.$store.dispatch('dcam/setAssetSearchObj', this.delete())

      // this.filter(this.formItem)

      this.$emit('searchCtx', this.formItem)
      // 回显
      this.formItem.s_money.value = value
    },
    delete() {
      let resultObj = {}
      let complexSearch = false
      const searchObj = Object.assign({}, this.formItem)
      if (Object.keys(searchObj).some(k => isObject(searchObj[k]))) {
        complexSearch = true
      }
      // 清理无效查询项
      for (const k in searchObj) {
        if (complexSearch) {
          if (!searchObj[k].value) delete searchObj[k]
        } else {
          if (!searchObj[k]) delete searchObj[k]
        }
      }

      let _searchObj = {}
      if (complexSearch) {
        for (const k in searchObj) {
          _searchObj[k] = searchObj[k].value
        }
        // 记录筛选项
        // resultObj = Object.keys(searchObj).map(key => { return { k: key, v: searchObj[key] } })
      } else {
        _searchObj = Object.assign({}, searchObj)
      }
      resultObj = _searchObj
      return resultObj
    },
    // 重置按钮点击事件处理
    reset: function() {
      for (var t in formItem) {
        formItem[t].value = null
        formItem[t].valueName = null
      }
      formItem.s_money.value = ''
      formItem.s_money.valueName = ''
      formItem.s_selectMoney = { value: '', label: '操作符', valueName: '', hidden: true }
      formItem.s_purchaseDateBegin = { value: '', label: '购置日期起', valueName: '' }
      formItem.s_purchaseDateEnd = { value: '', label: '购置日期止', valueName: '' }
      formItem.s_maintenanceStartBegin = { value: '', label: '维保开始起', valueName: '' }
      formItem.s_maintenanceStartEnd = { value: '', label: '维保开始止', valueName: '' }
      formItem.s_maintenanceEndBegin = { value: '', label: '维保结束起', valueName: '' }
      formItem.s_maintenanceEndEnd = { value: '', label: '维保结束止', valueName: '' }
      if (this.managementOrgCode) {
        formItem.s_managementOrgCode.value = this.managementOrgCode
      }
      this.timeRangeMaintenanceStart = []
      this.timeRangeMaintenanceEnd = []
      this.timeRangePurchaseDate = []
      this.assetTypeCode = null
      this.formItem = clone(formItem)
      this.search()
    },
    onChange: function(val) {
      this.$parent.onResize()
    },
    onFilterItemClose: function(item) {
      if (item.k === 's_purchaseDateBegin' || item.k === 's_purchaseDateEnd') {
        this.formItem['s_purchaseDateBegin'] = { value: '', label: '购置日期起', valueName: '' }
        this.formItem['s_purchaseDateEnd'] = { value: '', label: '购置日期止', valueName: '' }
        this.timeRangePurchaseDate = []
      } else if (item.k === 's_maintenanceStartBegin' || item.k === 's_maintenanceStartEnd') {
        this.formItem['s_maintenanceStartBegin'] = { value: '', label: '维保开始起', valueName: '' }
        this.formItem['s_maintenanceStartEnd'] = { value: '', label: '维保开始止', valueName: '' }
      } else if (item.k === 's_maintenanceEndBegin' || item.k === 's_maintenanceEndEnd') {
        this.formItem['s_maintenanceEndBegin'] = { value: '', label: '维保结束起', valueName: '' }
        this.formItem['s_maintenanceEndEnd'] = { value: '', label: '维保结束止', valueName: '' }
      } else if (item.k === 's_bigTypeCode' || item.k === 's_middleTypeCode' || item.k === 's_smallTypeCode') {
        this.formItem['s_bigTypeCode'] = { value: null, label: '大分类', valueName: '' }
        this.formItem['s_middleTypeCode'] = { value: null, label: '中分类', valueName: '' }
        this.formItem['s_smallTypeCode'] = { value: null, label: '小分类', valueName: '' }
        this.assetTypeCode = null
      } else {
        formItem[item.k].value = null
        formItem[item.k].valueName = ''
        this.formItem[item.k] = clone(formItem[item.k])
      }

      this.formItem.s_belongs.value = this.belongs
      this.formItem.s_locked.value = this.locked
      this.formItem.s_categories.value = this.categories
      this.formItem.s_status.value = this.status
      this.formItem.s_statusCode.value = this.statusCode
      this.formItem.s_orgIds.value = this.orgIds
      this.formItem.s_specifications.value = this.specifications
      // this.filter(this.formItem)
      this.$emit('searchCtx', this.formItem)
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    },
    findParent(item, flattenTree) {
      const parentArr = [] // 存储所有的父级元素
      function find(item, flattenTree) {
        flattenTree.forEach(ele => {
          if (ele.code === item) {
            parentArr.unshift({ code: ele.code, name: ele.title })
            find(ele.parentKey, flattenTree)
          }
        })
      }
      find(item, flattenTree)
      return parentArr
    }
  }
}
</script>
<style scoped>
</style>
